package com.wj.gulimall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wj.common.constant.AuthServerConstant;
import com.wj.common.utils.HttpUtils;
import com.wj.common.utils.R;
import com.wj.common.vo.MemberRespVo;
import com.wj.common.vo.SocialUser;
import com.wj.gulimall.authserver.config.WeiboProperties;
import com.wj.gulimall.authserver.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private WeiboProperties weiboProperties;

    @Resource
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", weiboProperties.getClient_id());
        map.put("client_secret", weiboProperties.getClient_secret());
        map.put("grant_type", weiboProperties.getGrant_type());
        map.put("redirect_uri", weiboProperties.getRedirect_uri());
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), new HashMap<>(), map);
        //2.处理
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode() == 0) {
                MemberRespVo data = oauthLogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                httpSession.setAttribute(AuthServerConstant.LOGIN_USER, data);
                log.info("登陆成功");
                return "redirect:http://gulimall.com";
            }
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
